// shop page
// ============

define(['zepto', 'utils', 'JST', 'page/mobile-bind', 'page/trading/coupon-select', 'page/trading/discount-code-select', 'wxshare', 'amountControl'], 
function($, utils, JST, mobileApp, couponSelect, discountCodeSelect, wxshare) {
  return {
    init: function(data) {
      
      this.model = {
        'product': data.product,
      }
      
      this.initPage(data)
      
      this.onOrderAmountChange()
      
      this.onCouponChange()
      
      this.onDiscountCodeChange()
      
      if(data.sites != null) this.bindSiteSelect(data.sites)
      
      couponSelect.init(__CTX__, this.model.product.id)
      
      this.bindOrderSubmitAction()
      
      discountCodeSelect.init(__CTX__, this.model.product.amount, this.model.product.type)
      
    },
    
    initPage: function(data) {
      // forbidden wx share
      wxshare.initShare(data.jsConfig, false)
      mobileApp.init(__CTX__)
    },

    // order amount change handler
    onOrderAmountChange: function() {

      that = this
      
      var $orderAmountInput = $("input[name='quantity']")

      $orderAmountInput.on("amountcontrol:change", function(e){
        var amount = $(this).val(), price= that.model.product.amount
        var couponAmount = $('[href="#coupon-select"]').find('.item-after').data('coupon-amount')
        that.calculateAmount(amount, price, couponAmount)
      })
    },

    // coupon select change handler
    onCouponChange: function() {

      that = this
      var $orderAmountInput = $("input[name='quantity']"), $totalCost=$(".total-cost")

      $(document).on('coupon:change:event', '[href="#coupon-select"]', function(event) {
        event.preventDefault()
        var couponAmount = $(this).find('.coupon-item').data('coupon-amount')
        var couponOnlineYear = $(this).find('.coupon-item').data('coupon-onlineyear')
        var discountAmount = $('.discount-item').data('discount-amount')
        var amount = 1, price= that.model.product.amount;
        that.calculateAmount(amount, price, couponAmount, discountAmount, couponOnlineYear)
      })
    },
    
   // discountCode select change handler
    onDiscountCodeChange: function() {

      that = this
      var $orderAmountInput = $("input[name='quantity']"), $totalCost=$(".total-cost")

      $(document).on('discountCode:change:event', '[href="#discount-code-select"]', function(event) {
        event.preventDefault()
        var couponAmount = $('.coupon-item').data('coupon-amount')
        var couponOnlineYear = $('.coupon-item').data('coupon-onlineyear')
        var discountAmount = $(this).find('.discount-item').data('discount-amount')
        var amount = 1, price= that.model.product.amount;
        that.calculateAmount(amount, price, couponAmount, discountAmount, couponOnlineYear)
      })
    },

    // calculate total cost
    calculateAmount: function(amount, price, couponAmount, discountAmount, couponOnlineYear) {
      if(couponOnlineYear) {
        var $totalCost=$(".total-cost")
        $totalCost.text(0);
      } else {
        if(!couponAmount) {
          couponAmount = 0;
        }
        if(!discountAmount) {
          discountAmount = 0;
        }
        var $totalCost=$(".total-cost")
        var cost = ( price * amount)
        if (couponAmount != undefined && couponAmount != null) {
          cost = ( price * amount )  - couponAmount - discountAmount > 0 ? (( price * amount )  - couponAmount - discountAmount) : 1;
        }
        $totalCost.text((cost / 100).toFixed(2))
      }
    },

    // order submit evvent handler
    bindOrderSubmitAction: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.button-order")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          if(data.type.value === 'others') {
            data = thatSubmit.onAppendOtherData(data)
          } else if(data.type.value === 'online' && that.model.product.onlineYear === "false" && false) {
            data = thatSubmit.onAppendOnlineData(data)
          }
          thatSubmit.onSubmitOrder(data)
        }
      })
      
    },
    
    bindSiteSelect: function(sites) {
      
      that = this
      
      var $siteSelector = $("input[name='siteSelector']")
      
      var displayValues = []
      var values = []
      
      for(var i in sites) {
        values.push(sites[i].id)
        displayValues.push(sites[i].name)
      }
      
      $siteSelector.picker({
        toolbarTemplate: '<header class="bar bar-nav">\
                            <button class="button button-link pull-right close-picker">确定</button>\
                            <h1 class="title">请选择门店</h1>\
                         </header>',
        cols: [
          {
            textAlign: 'center',
            values: values,
            displayValues: displayValues
          }
        ],
        formatValue: function (picker, value, displayValue){
          $(this.input).next().val(value)
          return displayValue
        }
      });
      
    },

    // init data
    onInitData: function() {
      return {
        'productId': {
          'value': this.model.product.id,
          'message': '产品id不能为空'
        },
        'type': {
          'value': this.model.product.type,
          'message': '产品类型不能为空'
        },
        'contact.contactPerson': {
          'value': $('input[name="contactName"]').val().trim(),
          'message': '请填写联系人姓名'
        },
        'contact.contactPhone': {
          'value': $('input[name="contactMobile"]').val().trim(),
          'message': '请填写联系人手机'
        },
        'amount': {
          'value': 1,   //$('input[name="quantity"]').val().trim()
          'message': '数量不能为空'
        }
      }
    },
    
    onAppendOtherData: function(data) {

        data.identificationCard = {
          'value': $('input[name="identificationCard"]').val()
        }
        data.address = {
          'value': $('textarea[name="address"]').val()
        }
        return data;
    },
    
    onAppendOnlineData: function(data) {
      // data.height = {
      //   'value': $('input[name="height"]').val().trim()
      // }
      // data.weight = {
      //   'value': $('input[name="weight"]').val().trim()
      // }
      // data.hourDifference = {
      //   'value': $('input[name="hourDifference"]').val().trim()
      // }
      return data;
    },

    onAppendData: function(data) {
      
      data.couponId = {
        'value': $('[href="#coupon-select"]').find('.item-after').data('selected-coupon')
      }
      data.comment = {
        'value': $('textarea[name="comment"]').val()
      }
      
      if($('input[name="discountCode"]').val() != null) {
    	data.discountCode = {
          'value': $('input[name="discountCode"]').val().trim()	  
        }  
      }
      
      var $site = $("input[name=site]")
      
      if($site.length > 0 && $site.val() != null && $site.val() != '') {
        data.siteId = {
          'value': $site.val()
        }
      }
      
      data.wechatNumber = {
         'value': $('input[name="wechatNumber"]').val().trim()
      }
      
      return data;
    },

    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)

      if (data.amount.value == 0) {
        return $.toast('请填写正确的数量') 
      }
      
      var $site = $("input[name=site]")
      if($site.length > 0) {
        if($site.val() == null || $site.val() == '') {
          return $.toast('请选择门店')
        }
      }
      
      if(!(that.model.product.type == 'others')) {
    	  var $wechatNumber = $("input[name=wechatNumber]")
          var patrn = /^['?!=%;&\$a-zA-Z\d_-]{6,20}$/;
          if($wechatNumber.val() == '' || !patrn.test($wechatNumber.val().trim())) {
        	  return $.toast('请输入正确的微信号')
          }
      }
      
      
      if(data.type.value === 'others') {
    	  var $identificationCard = $("input[name=identificationCard]")

          if($identificationCard.val() == null || $identificationCard.val() == '') {
        	  return $.toast("身份证号不可为空")
          }
    	  var regIdCard=/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
          if(!regIdCard.test($identificationCard.val().trim())) {
        	  return $.toast("请输入正确的身份证号")
          }
    	  
    	  var $address = $("textarea[name=address]")
    	  if($address.val() == null || $address.val() == '') {
    		  return $.toast("地址不可为空")
    	  }
      } 
      
      if(that.model.product.type === 'online' && that.model.product.onlineYear === "false" && false) {
        // var height = $("input[name=height]").val().trim();
        // if(height == null || height == '') {
          // $.toast("身高不可为空", 3000);
          // return false;
        // } else {
          // var regp = new RegExp("^[0-9]*$");
          // if(!regp.test(height)) {
            // $.toast("请输入正确的身高", 3000);
            // return false;
          // }
        // }

        // var weight = $("input[name=weight]").val().trim();
        // if(weight == null || weight == '') {
          // $.toast("体重不可为空", 3000);
          // return false;
        // } else {
          // var regw =  /^\+?(\d*\.\d{1})$/;
          // if(!regw.test(weight)) {
            // $.toast("体重精确到小数点后一位", 3000);
        //     return false;
        //   }
        // }
        
        // var hourDifference = $("input[name=hourDifference]").val().trim();
        // if(hourDifference) {
        //   var regh = new RegExp("^[0-9]*$");
          // if(!regh.test(hourDifference)) {
          //   $.toast("请输入正确的时差(正整数)", 3000);
          //   return false;
          // }
        // }
        
        // var remark = $("textarea[name=comment]").val().trim();
        // if(remark && remark.length>30) {
        // 	$.toast("备注不能超过30个字符", 3000);
        //     return false;
        // }
      }

      return true
    },

    onSubmitOrder: function(data) {
      var that = this;
      $.showPreloader('正在提交订单')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/orders',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('创建订单成功')
          setTimeout(function() {
            if(result.data.orderType === 'others') {
              window.location.href = __CTX__.root + '/orders/shipping-address?order=' + result.data.orderId;
            }else {
              that.formSubmit(window.__CTX__.root + '/pay3', {'order': result.data.orderId}, 'POST').submit();
            }
          }, 1000)
        }, function(result) {
          $.toast(result.message || '订单创建失败')
        })
      })
    },

    formSubmit: function (url, data, method) {
        if (method == null) method = 'POST';
        if (data == null) data = {};

        var form = $('<form>').attr({
            method: method,
            action: url
        }).css({
            display: 'none'
        });

        var addData = function (name, data) {
            if ($.isArray(data)) {
                for (var i = 0; i < data.length; i++) {
                    var value = data[i];
                    addData(name + '[]', value);
                }
            } else if (typeof data === 'object') {
                for (var key in data) {
                    if (data.hasOwnProperty(key)) {
                        addData(name + '[' + key + ']', data[key]);
                    }
                }
            } else if (data != null) {
                form.append($('<input>').attr({
                    type: 'hidden',
                    name: String(name),
                    value: String(data)
                }));
            }
        };

        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                addData(key, data[key]);
            }
        }
        return form.appendTo('body');
    }
    
  }
})